<template>
	<scroll-view @scrolltolower="scrolltolower" :scroll-y="true" :class="pageClass" :style="pageStyle" v-if="pageReady" >
		<moxi-nav :set="navSet"></moxi-nav>

		<view style="display: flex;flex-direction: column;height: 100%;">
			<view class="tore-box">
				
				<view class="tore-content"
				:style="activeIndex === item.id"
					v-for="(item,index) in list" :key="item.id" @click="handleClick(item.id,index)" >
					<view @click="message(index)">
						<view style="padding: 12px;">
						<view class="store-and-distance">
							<text style="width: 76%;font-size: 16px;font-weight:bolder;">
								{{item.name}}
							</text>
							<text  style="font-size: 12px;font-weight: normal;color: #999999;word-break: break-all;" v-if="item.distance > -1">
								{{item.distance}}km
							</text>
						</view>

						<view class="business-reservation">
							<view style="display: flex;gap: 8px;" >
								<u-tag v-if="item.isOpen === 1" text="营业中" size="mini" type="error" :bgColor="colorList[4]"
									:borderColor="colorList[4]"></u-tag>
									<u-tag v-else text="店铺暂未营业" size="mini" type="error"  bgColor="#C6C7CB"
										borderColor="#C6C7CB"></u-tag>
								<!-- <u-tag text="可预约" size="mini" type="error" :bgColor="colorList[16]"
									:borderColor="colorList[16]" :color="colorList[1]" :show="item.reservation"></u-tag> -->
							</view>
						</view>

						<view style="width: 76%;">
							<text style="font-size: 12px;font-weight: normal;color: #999999;word-break: break-all;">
								{{item.address}}
							</text>
						</view>

						<view style="display: flex;justify-content: space-between;align-items: center;">
							<view>
								<text v-if="opentime[index]" style="font-size: 12px;letter-spacing: 0.32px;color: #999999;">
									<text>营业时间：</text>
									<text style="margin-right: 3px;" v-for="(time,index) in JSON.parse(item.opentime)">
										 {{time[0]}}-{{time[1]}} 
										<!-- <view v-for="(h) in time">{{h}}</view> -->
									</text>
								</text>
								<text v-else style="font-size: 12px;letter-spacing: 0.32px;color: #999999;">
									<text>暂无营业时间</text>
								</text>
								
							</view>
							<view style="display: flex;gap: 12px;z-index: 10;">
								<view class="store-icon" @click.stop="phoneClick(item)">
									
									<u-icon name="phone-fill" size="16"></u-icon>
									
								</view>
								
								<view class="store-icon" @click.stop="mapClick(item)">
									<u-icon name="map-fill" size="16"></u-icon>
								</view>
							</view>
						</view>
					</view>
					</view>
				</view>
			</view>
		</view>
		<!-- <view class="placeOrder">
			<u-button style="height: 48px;border-radius: 8px;" :color="colorList[4]" text="预约下单" v-if="activeIndex !== -1"
				@click="placeOrderClick">
			</u-button>
		</view> -->
		<moxi-tabbar :set="tabbar" v-if="tabbar.index_id"></moxi-tabbar>
	</scroll-view>

</template>

<script>
import parse from '../uni_modules/uview-ui/libs/config/props/parse';

	export default {
		data() {
			return {
				opentime:[],
				list: [],
				mid: 0,
				activeIndex: -1,
				info: {
					page: 1,
					page_num: 5
				},
				hasMore: true,
				merchantlocation:{
					'lat':0,
					'lng':0
				},
				location:{
					'lat':0,
					'lng':0
				},
				juli:[],
				merchantData:[],
				isGetlocation:false,
				
			}
		},
		onLoad() {
			this.get(1);
		},
		computed: {
			getMid(mid) {
				if (this.activeIndex === -1) return null;
				const selectedItem = this.list.find(item => item.id === this.activeIndex);
				// console.log(selectedItem);
				return selectedItem ? selectedItem.id : null;
			}
		},
		methods: {
			message(key){
				if(this.list[key].isOpen == 0){
					this.msg('店铺暂未营业')
					// uni.showToast({
					// 	title: '已打烊',
					// 	icon: 'none'
					// })
				}
				
			},
			
			vincentyDistance(lat1, lon1, lat2, lon2) {
				    const a = 6378137; // 地球长半轴（米）
				    const f = 1 / 298.257223563; // 地球扁率
				    const b = (1 - f) * a;
				    const L = (lon2 - lon1) * (Math.PI / 180);
				    const U1 = Math.atan((1 - f) * Math.tan(lat1 * (Math.PI / 180)));
				    const U2 = Math.atan((1 - f) * Math.tan(lat2 * (Math.PI / 180)));
				    let sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
				    let sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);
				    let lambda = L;
				    let lambdaP;
				    let iterLimit = 100;
					let cosSqAlpha;
					let cosSigma;
					let sigma;
					let sinAlpha;
					let sinLambda;
					let cosLambda;
					let sinSigma;
					let cos2SigmaM;
				    do {
				         sinLambda = Math.sin(lambda);
				         cosLambda = Math.cos(lambda);
				         sinSigma = Math.sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda) +
				            (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda));
				        if (sinSigma === 0) {
				            return 0; // 两点重合
				        }
				         cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
				         sigma = Math.atan2(sinSigma, cosSigma);
				         sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
				         cosSqAlpha = 1 - sinAlpha * sinAlpha;
				         cos2SigmaM;
				        if (cosSqAlpha!== 0) {
				            cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
				        } else {
				            cos2SigmaM = 0;
				        }
				        const C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
				        lambdaP = lambda;
				        lambda = L + (1 - C) * f * sinAlpha *
				            (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
				    } while (Math.abs(lambda - lambdaP) > 1e-12 && --iterLimit > 0);
				
				    if (iterLimit === 0) {
				        return NaN; // 迭代未收敛
				    }
				
				    const uSq = cosSqAlpha * (a * a - b * b) / (b * b);
				    const A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
				    const B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
				    const deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
				        B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
				    const s = b * A * (sigma - deltaSigma);
				
				    return s;
				
			},
			
			get(page) {
				if (!this.hasMore) {
					return false
				}
				if (page) {
					this.info.page = page;
				}
				// //先获取当前用户坐标
					this.moxiPost("/plugin/order/index/merchant/getMerchant", this.info, (res) => {
						console.log(res.data);
						for (let k in res.data.data) {
							res.data.data[k].distance = -1;
							this.list.push(res.data.data[k])
							this.opentime.push(JSON.parse(res.data.data[k]['opentime']))
							// this.juli.push({mid:res.data.data[k]['mid'],distance:s})
							
					
						}
						console.log(res.data);
						
						this.getDis()
						
						// uni.setStorageSync('plugin_order_distance',this.juli)
						// // console.log(this.juli);
						// const instance = uni.getStorageSync('plugin_order_distance')
						// console.log('instance:',instance);
						//获取当前的时间
						const now = new	Date();
						
						const timeNow = parseInt(now.toString().slice(16,21).replace(/:/g, ''));
						// 循环获取到商家的营业时间并转化成 int
						        this.list.forEach((item) => {
						            item.isOpen = 0; // 先默认打烊
						            if (item['opentime']!== null && item['opentime']!== undefined) {
						                JSON.parse(item['opentime']).forEach((time) => {
						                    const startime = parseInt(time[0].toString().replace(/:/g, ''));
						                    const endtime = parseInt(time[1].toString().replace(/:/g, ''));
						                    // 开始判断当前时间
						                    if (timeNow > startime && timeNow < endtime) {
						                        item.isOpen = 1;
						                    }
						                });
						            }
						        });
					})
					
					
			
				
					
				
				
			},
			getDis(){
				if(!this.isGetlocation){
					this.moxiGetLocation((lc)=>{
						console.log(lc);
						this.location.lat = lc.latitude;
						this.location.lng = lc.longitude;	
						this.isGetlocation = true;
						this.buildDis(this.location.lat,this.location.lng)
					
					});
				}else{
					this.buildDis(this.location.lat,this.location.lng)
					}
			},
			buildDis(lat,lng){
				console.log(lat);
				console.log(lng);
				for(let k in this.list){
					this.list[k].distance = this.getDistance(lat,lng,this.list[k].la,this.list[k].ln)
					
					console.log(this.list[k].distance);
				}
			},
			handleClick(mid,key) {
				if (this.activeIndex === mid) {
					this.activeIndex = -1;
				} else {
					this.activeIndex = mid;
				}
				
				console.log(this.list)
				if(this.list[key].isOpen === 0){
					return false;
				}else{
					console.log('这是：mid=>',mid);
					this.navto('/plugin_order/goods?mid=' + mid + '&instance=' + this.list[key].distance)
					// console.log('这个mid是：', mid);
					console.log('这个距离是：', this.list[key].distance);
				}
				
			},

			scrolltolower() {
				if (this.hasMore) {
					this.info.page++;
					this.get()
				}
			},

			//拨打电话
			phoneClick(item) {
				if (!item.tel) {
					uni.showToast({
						title: '暂无联系电话',
						icon: 'none'
					});
					return;
				}
				// uni.makePhoneCall({
				// 	phoneNumber: item.tel
				// });
				// #ifdef MP-ALIPAY
				my.makePhoneCall({
					number: item.tel,
					success: () => {
						console.log('支付宝拨打电话成功');
					}
				});
				// #endif
				// #ifndef MP-ALIPAY
				uni.makePhoneCall({
					phoneNumber: item.tel
				});
				// #endif
			},

			//地图导航
			mapClick(item) {
				if (!item.ln || !item.la) {
					uni.showToast({
						title: '暂无位置信息',
						icon: 'none'
					});
					return;
				}
				const latitude = Number(item.la);
				const longitude = Number(item.ln);
				const name = item.address || '目的地';
				// #ifdef MP-ALIPAY
				my.openLocation({
					latitude,
					longitude,
					name,
					address: item.address || '',
					success: () => console.log('支付宝地图打开成功'),
					fail: (err) => console.error('支付宝地图打开失败', err),
				});
				// #endif

				// #ifndef MP-ALIPAY
				uni.openLocation({
					latitude,
					longitude,
					name,
					success: () => console.log('地图打开成功'),
					fail: (err) => console.error('地图打开失败', err),
				});
				// #endif
			},

			placeOrderClick() {
				console.log('这是this.getmid:',this.getMid);
				if (!this.getMid) return;
				// 跳转到商品页面
				this.navto('/plugin_order/goods?mid=' + this.getMid)
			},

		}
	}
</script>

<style lang="scss" scoped>
	.tore-box {
		display: flex;
		flex-direction: column;
		// margin-bottom: 60px;
		padding: 0 12px;
		overflow: auto;
		gap: 12px;
	}

	.tore-content {
		border-radius: 6px;
		background: #FFFFFF;
		box-sizing: border-box;
		// border: 1px solid rgb(0 0 0 / 0%);
		border-color: #F5F5F5;
		transition: all 0.3s ease;
		margin-top: 10px;
	}

	.show-border {
		border: 1px solid;
		// border-color: #ff0000;
	}

	.tore-content .store-and-distance {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.tore-content .business-reservation {
		display: flex;
		margin-top: 4px;
	}

	.tore-content .store-icon {
		width: 24px;
		height: 24px;
		background: #F5F5F5;
		border-radius: 99px;
		display: flex;
		justify-content: center;
		cursor: pointer;
		
	}

	.placeOrder {
		color: white;
		position: sticky;
		bottom: 0px;
		padding: 0px 12px;
	}
</style>